const ProductModel = require('../../models/ProductModel');

const ProductService = {
  // 添加
  add: async data => {
    const { name, type, content, img, desc } = data;
    const result = await ProductModel.create({ name, type, content, img, desc });
    return result;
  },
  // 编辑
  edit: async (_id, data) => {
    const result = await ProductModel.updateOne({ _id }, { ...data, updateTime: new Date() });
    if (result.nModified === 0) {
      return false;
    } else {
      const edit = await ProductModel.findById(_id, ['name', 'type', 'content', 'img', 'desc']);
      return edit;
    }
  },
  // 删除
  delete: async _id => {
    const result = await ProductModel.deleteOne({ _id });
    return result;
  },
  // 查询
  findById: async _id => {
    console.log(_id);
    const result = await ProductModel.findOne({ _id }, ['_id', 'name', 'type', 'content', 'img', 'desc', 'updateTime', 'createTime']);
    return result;
  },
  // 列表
  list: async ({ page = 1, pageSize = 10 }) => {
    const result = await ProductModel.find({}, ['_id', 'name', 'type', 'content', 'img', 'desc', 'updateTime', 'createTime'])
      .skip((page - 1) * pageSize)
      .limit(pageSize);
    const count = await ProductModel.countDocuments();
    return {
      row: result,
      count,
    };
  },
};

module.exports = ProductService;
